package com.huluobo.a2203monthdemo.news

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2203monthdemo.R
import com.huluobo.a2203monthdemo.databinding.ActivityAddNewsBinding
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class AddNewsActivity : BaseActivity<ActivityAddNewsBinding, NewsViewModel>() {
    override fun initData() {
        viewModel.addNewsSuccess.observe(this){
            ToastUtils.showLong("提交新闻成功")
            finish()
        }
    }

    override fun initView() {
        binding.addNewsHeader.headerTitle.text = "添加新闻"
        binding.addNewsHeader.headerBack.setOnClickListener { finish() }
        binding.addNewsCommit.setOnClickListener {
            //    {
//        "newsId": 0,
//        "newsTime": "string",
//        "newsTitle": "string",
//        "newsValue": "string",
//        "tagId": 0,
//        "userId": 0
//    }
            val titleString = binding.addNewsTitlesEt.text.toString()
            val valueString = binding.addNewsValueEt.text.toString()
            if (titleString.isNotEmpty() && valueString.isNotEmpty()) {
                val map = mutableMapOf<String, Any>()
                map[Const.PARAM_NEWS_TIME] = getTime()
                map[Const.PARAM_NEWS_TITLE] = titleString
                map[Const.PARAM_NEWS_VALUE] = valueString
                map[Const.PARAM_USER_ID] = SPUtils.getInstance().getInt(Const.PARAM_USER_ID)

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                viewModel.addNews(body)
            } else {
                binding.addNewsTitlesEt.error = "标题或者内容不能为空"
            }

        }
    }
}